package com.example.easytts.security

import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.security.Keys
import java.util.*
import javax.crypto.SecretKey

object JwtUtil {
    private val key: SecretKey = Keys.hmacShaKeyFor(
        "easytts-jwt-secret-key-12345678901234567890123456789012easytts-jwt-secret-key-1234567890123456".toByteArray()
    )
    private const val EXPIRE_MILLIS: Long = 7 * 24 * 60 * 60 * 1000 // 7天

    fun generateToken(username: String, roles: List<String>, expireMillis: Long = EXPIRE_MILLIS): String {
        val now = Date()
        val expiry = Date(now.time + expireMillis)
        return Jwts.builder()
            .setSubject(username)
            .claim("roles", roles)
            .setIssuedAt(now)
            .setExpiration(expiry)
            .signWith(key, SignatureAlgorithm.HS512)
            .compact()
    }

    fun getUsername(token: String): String? {
        return try {
            val claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token)
            claims.body.subject
        } catch (e: Exception) {
            println("JWT parse error for username: ${e.message}")
            null
        }
    }

    fun getRoles(token: String): List<String> {
        return try {
            val claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token)
            val roles = claims.body["roles"]
            if (roles is List<*>) roles.filterIsInstance<String>() else emptyList()
        } catch (e: Exception) {
            println("JWT parse error for roles: ${e.message}")
            emptyList()
        }
    }
} 